import { appTasks, OhosAppContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { hvigor } from '@ohos/hvigor'

// 为根节点添加一个afterNodeEvaluate hook 在hook中修改app.json5的内容并使能
hvigor.getRootNode().afterNodeEvaluate(rootNode => {
  // 获取app插件的上下文对象
  const appContext = rootNode.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext;
  // 通过上下文对象获取从app.json5文件中读出来的obj对象
  const appJsonOpt = appContext.getAppJsonOpt();
  // 修改obj对象为想要的，此处举例修改app中的versionCode
  appJsonOpt['app']['versionCode'] = 1000001;
  // 将obj对象设置回上下文对象以使能到构建的过程与结果中
  appContext.setAppJsonOpt(appJsonOpt);
})

// 测试插件
function helloHarmonyOS() {
  return {
    pluginId: 'HelloHarmonyOS',
    apply(pluginContext) {
      pluginContext.registerTask({
        // 编写自定义任务
        name: 'HelloHarmonyOS',
        run: (taskContext) => {
          console.log('Hello HarmonyOS!');
        }
      })
    }
  }
}

// 实现自定义插件
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        // 注册模块级任务
        hapTask(currentNode);
      });
    }
  };
}

function hapTask(currentNode: HvigorNode) {
  // 等待全部节点加载完成之后获取子节点信息
  currentNode.subNodes((node: HvigorNode) => {
    // 获取hap模块上下文信息
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    const moduleName = hapContext?.getModuleName();
    hapContext?.targets((target: Target) => {
      const targetName = target.getTargetName();
      const outputPath = target.getBuildTargetOutputPath();
      // 禁用任务
      //node.getTaskByName(`${target.getTargetName()}@SignHap`)?.setEnable(false);
      node.registerTask({
        // 任务名称
        name: `${targetName}@onlineSignHap`,
        // 任务执行逻辑主体函数
        run() {
          console.log('HelloHarmonyOS customPlugin');
        },
        // 配置前置任务依赖
        dependencies: [`${targetName}@PackageHap`],
        // 配置任务的后置任务依赖
        postDependencies: ['assembleHap']
      });
    });
  });
}


export default {
  /* Built-in plugin of Hvigor. It cannot be modified. */
  system: appTasks,

  /* Custom plugin to extend the functionality of Hvigor. */
  plugins: [
    helloHarmonyOS(),
    customPlugin()
  ]
}
